package com.xiumu.service.blog.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiumu.dao.blog.BlogPostTagDao;
import com.xiumu.pojo.blog.entity.BlogPostTag;
import com.xiumu.service.blog.BlogPostTagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文章与标签的关联表 Service 接口实现
 *
 * @author XiuMu
 * @Date 2023-01-30 14:21:26
 */
@Service
public class BlogPostTagServiceImpl extends ServiceImpl<BlogPostTagDao, BlogPostTag> implements BlogPostTagService {

    @Override
    public List<BlogPostTag> listByPostId(Long postId) {
        return list(Wrappers.lambdaQuery(BlogPostTag.class).eq(BlogPostTag::getPostId, postId));
    }

    @Override
    public List<BlogPostTag> listByPostId(List<Long> postId) {
        return list(Wrappers.lambdaQuery(BlogPostTag.class).in(BlogPostTag::getPostId, postId));
    }

    @Override
    @Transactional
    public boolean updatePostTag(Long postId, List<String> tagList) {
        if (CollUtil.isNotEmpty(tagList)){
            List<BlogPostTag> postTagList = listByPostId(postId);
            // 过滤出需要删除的标签
            List<Long> deleteIdList = postTagList.stream().filter(postTag -> !tagList.contains(postTag.getTagName())).map(BlogPostTag::getId).toList();
            // 过滤出需要新增的标签
            tagList.removeIf(tag -> postTagList.stream().anyMatch(postTag -> postTag.getTagName().equals(tag)));
            List<BlogPostTag> addList = tagList.stream().map(tag -> new BlogPostTag(postId, tag)).toList();
            removeBatchByIds(deleteIdList);
            saveBatch(addList);
        }
        return true;
    }
}




